import javax.mail.*;
import javax.mail.internet.*;
import java.io.InputStream;
import java.util.Properties;

public class EmailSender {

    public static void sendEmail(String host, int port, String username, String password, String to,
                                 String subject, String content) {
        Properties props = new Properties();
        props.put("mail.smtp.host", host); // SMTP服务器地址
        props.put("mail.smtp.port", port); // SMTP服务器端口
        props.put("mail.smtp.auth", "true"); // 是否需要用户认证
        props.put("mail.smtp.ssl.enable", "true"); // 启用SSL
        props.put("mail.smtp.ssl.trust", host); // 信任SMTP服务器

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username)); // 设置发件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置收件人
            message.setSubject(subject); // 设置邮件主题
            message.setText(content); // 设置邮件正文

            Transport.send(message); // 发送邮件
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败：" + e.getMessage());
        }
    }


    public static void main(String[] args) {
        ClassLoader classLoader = EmailSender.class.getClassLoader();
        try (InputStream is = classLoader.getResourceAsStream("config.properties")) {
            Properties properties = new Properties();
            properties.load(is);
            String smtpServer = properties.getProperty("smtp_server");
            int port = Integer.parseInt(properties.getProperty("port"));
            String password = properties.getProperty("password");
            String from = properties.getProperty("from");
            String to = properties.getProperty("to");
            String subject = properties.getProperty("subject");
            String content = properties.getProperty("content");
            sendEmail(smtpServer, port, from, password, to, subject, content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
